package org.mics.lang.image;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;

/**
 * 图片工具类	
 * @author mics
 * @date 2020年10月9日
 * @version  1.0
 */
public class ImageUtils {

	
	/**
	 * 缩放图片到指定尺寸
	 * @param srcImage 源图片
	 * @param width  缩放到指定宽度
	 * @param height 缩放到指定高度
	 * @param equalScale 等比例
	 * @return 缩放之后的图片
	 */
	public BufferedImage zoom(BufferedImage srcImage, int width, int height, boolean equalScale) {
		BufferedImage target = null;
		if(srcImage == null) {
			throw new ImageException("重置源图片不能为空");
		}
		//重置宽度比例
        double sx = (double) width / srcImage.getWidth(); 
      //重置高度比例
        double sy = (double) height / srcImage.getHeight();
        // 等比缩放
        if (equalScale) {
            if (sx > sy) {
                sx = sy;
                width = (int) (sx * srcImage.getWidth());
            } else {
                sy = sx;
                height = (int)(sy * srcImage.getHeight());
            }
        }
        ColorModel cm = srcImage.getColorModel();
        WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
        boolean alphaPremultiplied = cm.isAlphaPremultiplied();
        target = new BufferedImage(cm, raster, alphaPremultiplied, null);
        Graphics2D g = target.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.drawRenderedImage(srcImage, AffineTransform.getScaleInstance(sx, sy));
        g.dispose();
        return target;
	}
}
